package com.ruoyi.web.controller.activiticonfig;

import com.ruoyi.common.core.domain.model.LoginUser;
import org.activiti.bpmn.model.*;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.delegate.event.impl.ActivitiEntityEventImpl;
import org.activiti.engine.impl.cmd.CompleteTaskCmd;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.util.ProcessDefinitionUtil;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.List;

@Component
public class ComActivitiEventListener implements ActivitiEventListener, Serializable {

   
    
    
    @Override
    public void onEvent(ActivitiEvent event) {
        switch (event.getType()) {
            case TASK_CREATED:
                System.out.println(event);
                if (!(event instanceof ActivitiEntityEventImpl)) {
                    return;
                }
                ActivitiEntityEventImpl activitiEntityEventImpl = (ActivitiEntityEventImpl) event;
                Object entity = activitiEntityEventImpl.getEntity();
                if (!(entity instanceof TaskEntity)) {
                    return;
                }
                TaskEntity taskEntity = (TaskEntity) entity;
                this.onCreate(taskEntity);
                break;
            case CUSTOM:
                
            default:
                break;
        }

    }

    @Override
    public boolean isFailOnException() {
        return false;
    }

    private void onCreate(TaskEntity delegateTask) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        LoginUser loginUser = (LoginUser) principal;

        System.out.println(delegateTask);
        ExecutionEntity execution = delegateTask.getExecution();
        FlowElement currentFlowElement1 = execution.getCurrentFlowElement();
        Process process = ProcessDefinitionUtil.getProcess(delegateTask.getProcessDefinitionId());
        UserTask currentFlowElementTask = (UserTask) currentFlowElement1;
        List<SequenceFlow> incomingFlows = currentFlowElementTask.getIncomingFlows();
        SequenceFlow sequenceFlow = incomingFlows.get(0);
        FlowElement sourceFlowElement = sequenceFlow.getSourceFlowElement();
        
        if (sourceFlowElement instanceof StartEvent) { // 判断当前任务的前一个节点是否是StartEvent，即是否是第一个任务
          new CompleteTaskCmd(delegateTask.getId(), null).execute(Context.getCommandContext());// 执行完成命令
        }
    }

  
}